<template>
  <div class="post-detail">
    <div class="container">
      <!-- 返回按钮 -->
      <div class="back-button">
        <el-button @click="goBack" icon="el-icon-arrow-left" type="primary">返回论坛</el-button>
      </div>

      <!-- 加载状态 -->
      <el-card v-if="loading" class="loading-card">
        <div class="loading-content">
          <i class="el-icon-loading"></i>
          <span>加载中...</span>
        </div>
      </el-card>

      <!-- 帖子详情 -->
      <div v-else-if="post" class="post-content">
        <!-- 帖子主体 -->
        <el-card class="post-main">
          <div class="post-header">
            <div class="post-category">
              <el-tag :type="getCategoryType(post.category)" size="medium">
                {{ post.category }}
              </el-tag>
            </div>
            <div class="post-actions">
              <el-button type="text" :class="{ 'favorited': post.isCollection }" @click="toggleFavorite(post)"
                icon="el-icon-star-off">
                收藏 ({{ post.collection || 0 }})
              </el-button>
              <!-- <el-dropdown v-if="isAuthor" @command="handleCommand">
                <el-button type="text" icon="el-icon-more">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="edit">编辑帖子</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除帖子</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown> -->
            </div>
          </div>

          <h1 class="post-title">{{ post.title }}</h1>

          <div class="post-meta">
            <div class="author-info">
              <el-avatar :size="40" :src="post.avatar">
                {{ post.userName ? post.userName.slice(0, 1) : '?' }}
              </el-avatar>
              <div class="author-details">
                <div class="author-name">{{ post.userName || '未知用户' }}</div>
                <div class="post-time">{{ formatTime(post.createTime) }}</div>
              </div>
            </div>
            <div class="post-stats">
              <span class="stat-item">
                <i class="el-icon-view"></i>
                {{ post.views || 0 }} 浏览
              </span>
              <span class="stat-item">
                <i class="el-icon-chat-dot-round"></i>
                {{ post.comments || 0 }} 回复
              </span>
            </div>
          </div>

          <div class="post-content-body" v-html="post.summary"></div>

          <!-- 帖子图片 -->
          <div v-if="post.images && post.images.length > 0" class="post-images">
            <el-image v-for="(image, index) in post.images" :key="index" :src="image" :preview-src-list="post.images"
              class="post-image" fit="cover"></el-image>
          </div>
        </el-card>

        <!-- 回复列表 -->
        <el-card class="replies-section">
          <div class="replies-header">
            <h3>回复 ({{ repliesTotal }})</h3>
            <el-button type="primary" @click="showReplyForm = !showReplyForm">
              {{ showReplyForm ? '取消回复' : '我要回复' }}
            </el-button>
          </div>

          <!-- 回复表单 -->
          <div v-if="showReplyForm" class="reply-form">
            <el-form ref="replyForm" :model="replyForm" :rules="replyRules">
              <el-form-item prop="content">
                <el-input v-model="replyForm.content" type="textarea" :rows="4" placeholder="请输入回复内容..." show-word-limit
                  maxlength="500"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitReply" :loading="submittingReply">
                  发布回复
                </el-button>
                <el-button @click="cancelReply">取消</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 回复列表 -->
          <div v-if="replies.length === 0 && !showReplyForm" class="no-replies">
            <i class="el-icon-chat-dot-round"></i>
            <p>暂无回复，快来抢沙发吧！</p>
          </div>

          <div v-else class="replies-list">
            <div v-for="reply in replies" :key="reply.id" class="reply-item">
              <div class="reply-avatar">
                <el-avatar :size="36" :src="reply.avatar">
                  {{ reply.userName ? reply.userName.slice(0, 1) : '?' }}
                </el-avatar>
              </div>
              <div class="reply-content">
                <div class="reply-header">
                  <span class="reply-author">{{ reply.userName || '未知用户' }}</span>
                  <span class="reply-time">{{ formatTime(reply.createdAt) }}</span>
                  <el-button type="text" style="color: red;" @click="deleteReply(reply.id)">删除</el-button>
                </div>
                <div class="reply-text">{{ reply.content }}</div>
                <div class="reply-actions">
                  <el-button type="text" size="mini" @click="replyToReply(reply)">
                    回复
                  </el-button>
                </div>
              </div>
            </div>
            
            <!-- 分页组件 -->
            <div class="replies-pagination">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[5, 10, 20, 50]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="repliesTotal"
                background>
              </el-pagination>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 404状态 -->
      <el-card v-else class="not-found">
        <div class="not-found-content">
          <i class="el-icon-warning"></i>
          <h3>帖子不存在</h3>
          <p>该帖子可能已被删除或不存在</p>
          <el-button type="primary" @click="goBack">返回论坛</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getPostDetail } from '../api/forum'
import { getForumReply, createForumReply, deleteForumReplyBatch } from '../api/forum-reply'
import { addForumCollection, cancelCollection } from '@/api/forum-collection'
import { mapGetters } from 'vuex'
export default {
  name: 'PostDetail',
  data() {
    return {
      repliesTotal: 0,
      loading: true,
      showReplyForm: false,
      submittingReply: false,
      post: null,
      replies: [],
      // 分页相关数据
      currentPage: 1,
      pageSize: 10,
      replyForm: {
        content: ''
      },
      replyRules: {
        content: [
          { required: true, message: '请输入回复内容', trigger: 'blur' },
          { min: 5, message: '回复内容至少5个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    postId() {
      return this.$route.params.id
    },
    ...mapGetters(['user']),
    // isAuthor() {
    //   // 这里应该检查当前用户是否是帖子作者
    //   return this.post && this.post.author.id === this.getCurrentUserId()
    // }
  },
  methods: {
    getForumReply() {
      getForumReply({ 
        pageNum: this.currentPage, 
        pageSize: this.pageSize, 
        forumId: this.postId 
      }).then(res => {
        if (res.code === 200) {
          this.replies = res.data.rows || []
          this.repliesTotal = res.data.total
        }
      })
    },
    // 分页处理方法
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getForumReply()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getForumReply()
    },
    async loadPost() {
      this.loading = true
      try {
        const response = await getPostDetail(this.postId)
        this.post = response.data
        // 加载回复列表
        const replyResponse = await getForumReply({ pageNum: 1, pageSize: 100, forumId: this.postId })
        if (replyResponse.code === 200) {
          this.replies = replyResponse.data.rows || []
          this.repliesTotal = replyResponse.data.total
        }
      } catch (error) {
        this.$message.error('加载帖子失败')
        this.post = null
      } finally {
        this.loading = false
      }
    },

  async toggleFavorite(post) {
      try {
        if (post.isCollection) {
          const res = await cancelCollection({ forumId: post.id })
          if (res.code === 200) {
            post.isCollection = false
            post.collection = Math.max((post.collection || 0) - 1, 0)
            this.$message.success('已取消收藏')
          } else {
            this.$message.error(res.message || '取消收藏失败')
          }
        } else {
          const res = await addForumCollection({
            forumId: post.id,
            userId: this.user.userId,
            userName: this.user.userName,
            ...post
          })
          if (res.code === 200) {
            post.isCollection = true
            post.collection = (post.collection || 0) + 1
            this.$message.success('已收藏')
          } else {
            this.$message.error(res.message || '收藏失败')
          }
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    },

    async submitReply() {
      if (!this.$refs.replyForm) return
      
      this.$refs.replyForm.validate(async (valid) => {
        if (valid) {
          this.submittingReply = true
          try {
            const response = await createForumReply({
              forumId: this.postId,
              content: this.replyForm.content,
              ...this.user
            })
            
            if (response.code === 200) {
              this.$message.success('回复成功')
              this.replyForm.content = ''
              this.showReplyForm = false
              // 重新加载回复列表，回到第一页
              this.currentPage = 1
              this.getForumReply()
            }
          } catch (error) {
            this.$message.error('回复失败，请重试')
          } finally {
            this.submittingReply = false
          }
        }
      })
    },

    cancelReply() {
      this.showReplyForm = false
      this.replyForm.content = ''
      this.$refs.replyForm && this.$refs.replyForm.clearValidate()
    },

    replyToReply(reply) {
      this.showReplyForm = true
      this.replyForm.content = `@${reply.userName || '未知用户'} `
      this.$nextTick(() => {
        const textarea = this.$el.querySelector('.reply-form textarea')
        if (textarea) {
          textarea.focus()
          textarea.setSelectionRange(textarea.value.length, textarea.value.length)
        }
      })
    },

    handleCommand(command) {
      if (command === 'edit') {
        // this.$router.push(`/forum/edit/${this.post.id}`)
      } else if (command === 'delete') {
        this.deletePost()
      }
    },
    async deletePost() {
      try {
        await this.$confirm('确定要删除这个帖子吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await deleteForumReplyBatch(this.post.id)

        if (res.code === 200) {
          this.$message.success('帖子已删除')
          this.$router.push('/forum')
        } else {
          this.$message.error(res.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    async deleteReply(replyId) {
      try {
        await this.$confirm('确定要删除这条回复吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await deleteForumReplyBatch(replyId)
        if (res.code === 200) {
          this.getForumReply()
          this.$message.success('回复已删除')
        } else {
          this.$message.error(res.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    editReply(reply) {
      // 这里可以实现编辑回复的功能
      this.$message.info('编辑功能开发中')
    },

    isReplyAuthor(reply) {
      return reply.userId === this.getCurrentUserId()
    },

    getCurrentUserId() {
      return this.user.userId
    },

    getCategoryType(category) {
      const typeMap = {
        '养护经验': 'success',
        '领养心得': 'primary',
        '健康咨询': 'warning',
        '训练技巧': 'info',
        '其他交流': ''
      }
      return typeMap[category] || ''
    },

    formatTime(date) {
      if (!date) return ''
      const now = new Date()
      const diff = now - new Date(date)
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))

      if (days === 0) {
        const hours = Math.floor(diff / (1000 * 60 * 60))
        if (hours === 0) {
          const minutes = Math.floor(diff / (1000 * 60))
          return minutes <= 0 ? '刚刚' : `${minutes}分钟前`
        }
        return `${hours}小时前`
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return new Date(date).toLocaleDateString()
      }
    },

    goBack() {
      this.$router.push('/forum')
    }
  },

  mounted() {
    this.loadPost()
  },
}
</script>

<style scoped>
.post-detail {
  background: #f8f9fa;
  min-height: 100vh;
  padding: 20px 0;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.back-button {
  margin-bottom: 20px;
}

.loading-card,
.not-found {
  text-align: center;
  padding: 40px;
}

.not-found-content i {
  font-size: 64px;
  color: #ddd;
  margin-bottom: 20px;
  display: block;
}

.post-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.post-main {
  padding: 30px;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.post-actions .el-button.favorited {
  color: #f56c6c;
}

.post-title {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 20px 0;
  line-height: 1.4;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.author-name {
  font-weight: 600;
  color: #2c3e50;
}

.post-time {
  font-size: 14px;
  color: #909399;
}

.post-stats {
  display: flex;
  align-items: center;
  gap: 20px;
  font-size: 14px;
  color: #909399;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.post-content-body {
  line-height: 1.8;
  color: #2c3e50;
  font-size: 16px;
}

.post-content-body h3 {
  margin: 24px 0 12px 0;
  color: #2c3e50;
  font-weight: 600;
}

.post-content-body p {
  margin: 16px 0;
}

.post-images {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
  margin-top: 20px;
}

.post-image {
  width: 100%;
  height: 200px;
  border-radius: 8px;
}

.replies-section {
  padding: 30px;
}

.replies-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.replies-header h3 {
  margin: 0;
  color: #2c3e50;
}

.reply-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.no-replies {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.no-replies i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.replies-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.reply-item {
  display: flex;
  gap: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.reply-item:last-child {
  border-bottom: none;
}

.reply-content {
  flex: 1;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.reply-author {
  font-weight: 600;
  color: #2c3e50;
}

.reply-time {
  font-size: 14px;
  color: #909399;
}

.reply-text {
  color: #2c3e50;
  line-height: 1.6;
  margin-bottom: 8px;
}

.reply-actions {
  display: flex;
  gap: 12px;
}

.replies-pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.replies-pagination .el-pagination {
  padding: 0;
}
</style>